package com.ZeroCarbon.service.impl;

import com.ZeroCarbon.domain.dto.UsernameAndAvatarDTO;
import com.ZeroCarbon.domain.po.UserPost;
import com.ZeroCarbon.exception.BusinessLogicException;
import com.ZeroCarbon.mapper.UserPostMapper;
import com.ZeroCarbon.service.IUserPostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

import static com.ZeroCarbon.BusinessUtils.UserClientUtils.*;
import static com.ZeroCarbon.exception.BusinessLogicException.BUSY_EXCEPTION;
import static com.ZeroCarbon.exception.BusinessLogicException.ERROR_EXCEPTION;
import static com.ZeroCarbon.method.RemoteClientCall.OperationType.GET_AVATAR;
import static com.ZeroCarbon.method.RemoteClientCall.OperationType.GET_USERNAME;

/**
 * 用户记录关系实现类
 *
 * @since 2024-10-26
 */
@Service
@RequiredArgsConstructor
public class UserPostServiceImpl extends ServiceImpl<UserPostMapper, UserPost> implements IUserPostService {

    /**
     * 获取记录id对应用户信息
     *
     * @param id 记录id
     */
    @Override
    @GlobalTransactional
    public UsernameAndAvatarDTO getAvatarAndUsername(String id) throws BusinessLogicException {
        //记录用户id
        String userId = null;
        try {
            //获取记录id对应的用户id
            userId = Db.lambdaQuery(UserPost.class)
                    .eq(UserPost::getRecordId, id)
                    .one()
                    .getId();
        } catch (Exception e) {
            throw new BusinessLogicException(ERROR_EXCEPTION);
        }
        //远程调用获取用户头像和用户名
        Map<String, String> userClientInformation;
        try {
            //获取用户对应的用户名和头像
            userClientInformation = getUserClientInformation(userId,
                    GET_USERNAME,
                    GET_AVATAR);
        } catch (Exception e) {
            throw new BusinessLogicException(BUSY_EXCEPTION);
        }
        //创建对象并返回
        return new UsernameAndAvatarDTO(
                userId,
                userClientInformation.get(USERNAME),
                userClientInformation.get(AVATAR)
        );
    }
}
